/**
 * 工具类
 * @author big.A
 * @version 1.1.0
 **/

var tool = {

	// 检查是否登录，带来路页面
	checkLogin(refer, type) {
		if (this.checkLoginStatus() == false) {
			this.msg('请先登录');
			var page = '';
			if (refer) {
				page = {page:this.getCurrentRoute(), type : type || 'reLaunch'};
			}
			this.go('/pages/in/in', 'reLaunch', 1300, page);
		}else {
			return true;
		}
	},
	
	// 带返回来源
	backRefer: function() {
		let refer = uni.getStorageSync("refer");
		if (refer) {
			this.go(refer.page,refer.type);
		} else {
			this.go('/pages/index/index','reLaunch');
		}
	},
	
	// 带返回来源
	onback: function() {
		let refer = uni.getStorageSync('refer');
		if (refer) {
			this.go(refer.page,refer.type);
		} else {
			this.go('/pages/index/index','reLaunch');
		}
	},
	
	// 检查登录状态
	checkLoginStatus: function() {
		if (uni.getStorageSync("token")) {
			return true;
		} else {
			return false;
		}
	},

	// 异常返回
	errCallback: function(title) {
		uni.showModal({
			title: "",
			content: title || "参数异常",
			showCancel: false,
			confirmText: "确定",
			success() {
				uni.navigateBack();
			}
		})
	},

	// 验证手机号
	checkPhone: function(phone) {
		return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(phone);
	},


	// 弹窗toast
	msg: function(text, success, duration) {
		uni.showToast({
			title: text || "出错啦~",
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},

	// loading窗口
	loading: function(title, mask = true) {
		uni.showLoading({
			mask: mask,
			title: title || '请稍候...'
		})
	},

	
	// 获取当前页面路径和参数
	getCurrentRoute () {
		var pages = getCurrentPages() // 获取栈实例
		let currentRoute  = pages[pages.length-1].route; // 获取当前页面路由
		let currentPage = pages[pages.length-1]['$page']['fullPath'] //当前页面路径(带参数)
		return currentPage;
	},
	
	// 业务页面跳转支付页面
	goPay(order_no,isDelay) {
		// 清空来路
		uni.removeStorageSync('pay_refer');
		if (!order_no) {
			this.msg('订单号错误');
			return false;
		}
		if (!isDelay) {
			isDelay = 100;
		}
		let url = '/pages/payment/payment?order_no=' + order_no;
		// 存入来路页面
		uni.setStorageSync("pay_refer",this.getCurrentRoute());
		this.go(url,'navigateTo',isDelay);
	},
	
	// 支付后返回来路
	payBack: function() {
		let pay_refer = uni.getStorageSync('pay_refer');
		if (!pay_refer) {
			pay_refer = '/pages/ucenter/ucenter';
		}
		uni.redirectTo({
			url:pay_refer,
			complete() {
				uni.removeStorageSync('pay_refer');
			}
		})
	},
	
	
	// 页面跳转
	go: function(url, type, isDelay, refer,success, fail, complete) {
		if (!type) {
			type = 'navigateTo';
		}
		if (!success) {
			success = function() {};
		}
		if (!fail) {
			fail = function() {};
		}
		if (!complete) {
			complete = function() {};
		}
		let timer = 0;
		if (isDelay) {
			timer = 1000;
		}
		if (refer) {
			uni.setStorageSync('refer', refer);
		}else {
			uni.removeStorageSync('refer');
		}
		setTimeout(() => {
			switch (type) {
				case 'navigateTo':
					uni.navigateTo({
						url: url,
						success: success,
						fail: fail,
						complete: complete
					});
					break;
				case 'redirectTo':
					uni.redirectTo({
						url: url,
						success: success,
						fail: fail,
						complete: complete
					});
					break;
				case 'switchTab':
					uni.switchTab({
						url: url,
						success: success,
						fail: fail,
						complete: complete
					});
					break;
				case 'reLaunch':
					uni.reLaunch({
						url: url,
						success: success,
						fail: fail,
						complete: complete
					});
					break;
			}
		}, timer)
	},

	// 格式化手机号 - 星号隐藏中间4位
	formatNumber: function(num) {
		return num.length === 11 ? num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2') : num;
	},

	// 金额格式化，保留两位小数
	formatMoney: function(money) {
		return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,')
			.replace(/\,$/, '').split('').reverse().join('');
	},

	// 根据时间戳计算距离现在多少分钟/小时/天
	fromTime: function(time) {
		if (time < 90000000000) {
			time *= 1000;
		}
		var timer = new Date().getTime() - time;
		timer = parseInt(timer / 1000);
		if (timer < 180) {
			return '刚刚';
		} else if (timer >= 180 && timer < 3600) {
			return parseInt(timer / 60) + '分钟前';
		} else if (timer >= 3600 && timer < 86400) {
			return parseInt(timer / 3600) + '小时前';
		} else if (timer >= 86400 && timer < 2592000) {
			return parseInt(timer / 86400) + '天前';
		} else {
			return this.toDate(time, 'str');
		}
	},

	/**
	 * 当前客户终端类型
	 * --- 手机浏览器访问 wap
	 * --- 电脑浏览器访问 web
	 * --- 微信小程序访问 wxapp
	 * --- 微信服务号访问 wechat
	 * --- 苹果应用接口访问 isoapp
	 * --- 安卓应用接口访问 android
	 * @var string
	 */
	client: function() {
		try {
			let client = false;

			// 是否微信浏览器
			// #ifdef H5
			let ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				client = 'wechat'; // 微信中浏览器
			} else {
				client = 'wap'; // 普通浏览器中
			}
			// #endif

			// 是否微信小程序
			// #ifdef MP-WEIXIN
			client = 'wxapp'; // 微信小程序
			// #endif

			// 判断IOS或者安卓APP
			// #ifdef APP-PLUS
			client = 'app';
			platform = uni.getSystemInfoSync().platform;
			if (platform == 'ios') {
				client = 'iosapp';
			}
			if (platform == 'android') {
				client = 'android';
			}
			// #endif

			return client;
		} catch (e) {
			return null;
		}
	},
	// 判断是否是数字
	isNumber(val) {
		var regPos = /^\d+(\.\d+)?$/; //非负浮点数
		var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
		if (regPos.test(val) || regNeg.test(val)) {
			return true;
		} else {
			return false;
		}
	},
	// 判断是否为空
	isEmpty(value) {
		switch (typeof value) {
			case 'undefined':
				return true
			case 'string':
				if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true
				break
			case 'boolean':
				if (!value) return true
				break
			case 'number':
				if (value === 0 || isNaN(value)) return true
				break
			case 'object':
				if (value === null || value.length === 0) return true
				for (const i in value) {
					return false
				}
				return true
		}
		return false
	},
	
	//判断是否在微信中
	isWechat () {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			// console.log(‘是微信客户端‘)
			return true;
		} else {
			// console.log(‘不是微信客户端‘)
			return false;
		}
	},

}

module.exports = tool
